﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Compact13Notepad
{
    public partial class Compact13ToolsNotepad : Form
    {
        //This will be the keeper of the filename
        private OpenFileDialog op;
        private SaveFileDialog sf;
        private bool SaveCancelled = false;
        private bool textDirty;
        private bool TextDirty {
            get
            { return textDirty; }
            set
            {
                if (textDirty != value)
                {
                    textDirty = value;
                    CountCheckpoints();
                }
            }
        }

        private int searchStart = -1;
        private string searchFor { get; set; }
        private string replaceWith {get;set;}
        private bool searchTextFound { get; set; }
        private Stack<string> Checkpoints { get; set; }

        public Compact13ToolsNotepad()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            menuItem8.Checked = statusBar1.Visible;
            menuItem9.Checked = richTextBox1.WordWrap;
            ClearDialogs();

            saveMenuItem = menuItem27;
            searchFor = "";
            searchStart = -1;
            replaceWith = "";
            searchTextFound = false;
            TextDirty = false;
            Checkpoints = new Stack<string>();
            PlaceCenter();
            this.WindowState = FormWindowState.Maximized;
        }

        private void PlaceCenter()
        {
            int Left = (Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2;
            int Top = (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2;
            if (Left < 0)
                Left = 0;
            if (Top < 20)
                Top = 20;
            this.Left = Left;
            this.Top = Top;
        }

        private void NotYetImplemented()
        {
            MessageBox.Show("Function not yet implemented", "Compact13Notepad");
        }

 #region Help
        private void menuItem6_Click(object sender, EventArgs e)
        {
            NotYetImplemented();
        }


        private void menuItem7_Click(object sender, EventArgs e)
        {
            AboutBox.ShowAsDialog();
            this.BringToFront();
        }
 #endregion

#region View
        private void menuItem8_Click(object sender, EventArgs e)
        {
            NotYetImplemented();
        }
#endregion

#region Format
        private void menuItem9_Click(object sender, EventArgs e)
        {
            richTextBox1.WordWrap = !richTextBox1.WordWrap;
            menuItem9.Checked = richTextBox1.WordWrap;
        }

        private void menuItem10_Click(object sender, EventArgs e)
        {
            NotYetImplemented();
        }
#endregion

        private void menuItem11_Click(object sender, EventArgs e)
        {
            richTextBox1.Undo();
        }

        private void menuItem13_Click(object sender, EventArgs e)
        {
            cutMenuItem_Click(null,null);
        }

        private void menuItem14_Click(object sender, EventArgs e)
        {
            copypMenuItem_Click(null, null);
        }

        private void menuItem15_Click(object sender, EventArgs e)
        {
            
            pasteMenuItem_Click(null, null);
        }

        private void menuItem16_Click(object sender, EventArgs e)
        {
            deteteMenuItem_Click(null,null);
        }


        private void menuItem18_Click(object sender, EventArgs e)
        {
            //Couple of sanity checks
            if (searchFor == "")
                return;
            if (searchFor.Length > richTextBox1.Text.Length)
                return;
            searchStart = 0;
            searchTextFound = false;
            searchStart = this.richTextBox1.Text.IndexOf(searchFor, searchStart);
            if (searchStart != -1)
            {
                richTextBox1.SelectionStart = searchStart;
                richTextBox1.SelectionLength = searchFor.Length;
                searchStart += searchFor.Length + 1;
                searchTextFound = true;
            }
            else
                richTextBox1.SelectedText = "";
        }

        private void menuItem19_Click(object sender, EventArgs e)
        {
            //Couple of sanity checks
            if (searchStart < 0)
                menuItem18_Click(null, null);
            else if (searchStart + searchFor.Length > (richTextBox1.Text.Length - 1))
                return;
            if (searchFor == "")
                return;
            if (searchFor.Length > richTextBox1.Text.Length)
                return;
            searchTextFound = false;
            searchStart = this.richTextBox1.Text.IndexOf(searchFor, searchStart);
            if (searchStart != -1)
            {
                richTextBox1.SelectionStart = searchStart;
                richTextBox1.SelectionLength = searchFor.Length;
                searchStart += searchFor.Length + 1;
                searchTextFound = true;
            }
            else richTextBox1.SelectedText = "";
        }

        
        private void menuItem20_Click(object sender, EventArgs e)
        {
            if (searchFor == "")
                return;
            if (richTextBox1.Text == "")
                return;
            richTextBox1.SelectedText = "";
            searchTextFound = false;
            menuItem19_Click(null, null);
            if (richTextBox1.SelectedText == "")
                return;
            if (searchTextFound)
                richTextBox1.SelectedText = replaceWith;
        }

        private void menuItem21_Click(object sender, EventArgs e)
        {
            NotYetImplemented();
        }

        private void menuItem23_Click(object sender, EventArgs e)
        {
            selectAllMenuItem_Click(null, null);
        }

        private void menuItem24_Click(object sender, EventArgs e)
        {
            timeDateMenuItem_Click(null, null);
        }

        private void menuItem26_Click(object sender, EventArgs e)
        {
            newMenuItem_Click(null, null);
        }

        private void menuItem25_Click(object sender, EventArgs e)
        {
            openMenuItem_Click(null, null);
        }

        private void menuItem27_Click(object sender, EventArgs e)
        {
            saveMenuItem_Click(null, null);
        }

        private void menuItem28_Click(object sender, EventArgs e)
        {
            saveAsMenuItem_Click(null, null);
        }

        private void menuItem30_Click(object sender, EventArgs e)
        {
            NotYetImplemented();
        }

        private void menuItem31_Click(object sender, EventArgs e)
        {
            NotYetImplemented();
        }

        MenuItem saveMenuItem;
        private void menuItem1_Click(object sender, EventArgs e)
        {
            saveMenuItem.Enabled = TextDirty && (op.FileName != "");
        }

        private void menuItem33_Click(object sender, EventArgs e)
        {
            if (TextDirty)
            {
                DialogResult dr = MessageBox.Show("Save Changes?", "Compact13Notepad", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,MessageBoxDefaultButton.Button1);
                if (dr == System.Windows.Forms.DialogResult.Cancel)
                    return;
                else if (dr == System.Windows.Forms.DialogResult.Yes)
                {
                    SaveCancelled = false;
                    saveMenuItem_Click(null, null);
                    if (!SaveCancelled)
                    {
                        Application.Exit();
                    }
                }
                else //No
                    Application.Exit();
            }
            else
                Application.Exit();

        }

        /////////////////////////////////
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            TextDirty = true;
            CountCheckpoints();
        }
        private void TextNotDirty()
        {
            TextDirty = false;
        }

        private void ClearDialogs()
        {
            op = new OpenFileDialog();
            op.FileName = "";
            //op.CheckFileExists = true;
            //op.CheckPathExists = true;
            //op.ValidateNames = true;
            //op.Title = "Open Text File";
            op.Filter = "Text File (*.txt)|*.txt|Any file (*.*)|*.*";
            op.FilterIndex = 1;
            op.InitialDirectory = "\\";

            sf = new SaveFileDialog();
            sf.FileName = "";
            //sf.CheckFileExists = true;
            //sf.CheckPathExists = true;

            sf.Filter = "Text Fie (*.txt)|*.txt|Any file (*.*)|*.*";
            //sf.ValidateNames = true;
            //sf..Title = "Save Text File";
            sf.InitialDirectory = "\\";

            this.Text = "Compact 2013 Notepad: Untitled.Txt";
            TextDirty = false;
        }

        //////////////////////////////////
        private void saveMenuItem_Click(object sender, EventArgs e)
        {
            if (op.FileName == "")
                saveAsMenuItem_Click(null, null);
            else
            {
                sf.FileName = op.FileName;
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sf.FileName))
                {
                    sw.Write(richTextBox1.Text);
                }
                TextDirty = false;
            }
        }

        private void saveAsMenuItem_Click(object sender, EventArgs e)
        {

            ///Start at current directory
            if (sf.FileName != "") 
            {
                System.IO.FileInfo sfinf = new System.IO.FileInfo(sf.FileName);
                sf.InitialDirectory =sfinf.Directory.ToString(); 
            }
            else
            {
                sf.InitialDirectory = "\\";
            }

            DialogResult dr = sf.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                System.IO.FileInfo inf = new System.IO.FileInfo(sf.FileName);
                if (inf.Extension == "")
                    sf.FileName += ".txt";

                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sf.FileName))
                {
                    sw.Write(richTextBox1.Text);
                }
                op.FileName = sf.FileName;
                System.IO.FileInfo opinf = new System.IO.FileInfo(op.FileName);
                this.Text = "Compact 2013 Notepad: " + opinf.Name;
                TextDirty = false;

            }
            else
                SaveCancelled = true;
        }

        private void openMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr;
            if (TextDirty)
            {
                dr = MessageBox.Show("Save Changes?", "Compact13Notepad", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dr == System.Windows.Forms.DialogResult.Cancel)
                    return;
                else if (dr == System.Windows.Forms.DialogResult.Yes)
                {
                    SaveCancelled = false;
                    saveMenuItem_Click(null, null);
                    if (!SaveCancelled)
                    {
                        if (op.FileName == "")
                            //Default
                            op.InitialDirectory = "\\";
                        else
                        {
                            ///Start at current directory
                            System.IO.FileInfo inf = new System.IO.FileInfo(op.FileName);
                            op.InitialDirectory = inf.Directory.ToString(); ;
                        }

                        dr = op.ShowDialog();
                        if (dr == System.Windows.Forms.DialogResult.OK)
                        {
                            using (System.IO.StreamReader sr = new System.IO.StreamReader(op.FileName))
                            {
                                richTextBox1.Text = sr.ReadToEnd();
                            }
                            sf.FileName = op.FileName;
                            System.IO.FileInfo inf = new System.IO.FileInfo(op.FileName);
                            this.Text = "Compact 2013 Notepad: " + inf.Name;
                            TextDirty = false;
                        }
                    }
                }
                else
                {
                    if (op.FileName == "")
                        //Default
                        op.InitialDirectory = "\\";
                    else
                    {
                        ///Start at current directory
                        System.IO.FileInfo inf = new System.IO.FileInfo(op.FileName);
                        op.InitialDirectory = inf.Directory.ToString(); ;
                    }

                    dr = op.ShowDialog();
                    if (dr == System.Windows.Forms.DialogResult.OK)
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(op.FileName))
                        {
                            richTextBox1.Text = sr.ReadToEnd();
                        }
                        sf.FileName = op.FileName;
                        System.IO.FileInfo inf = new System.IO.FileInfo(op.FileName);
                        this.Text = "Compact 2013 Notepad: " + inf.Name;
                        TextDirty = false;
                    }
                }
            }
            else
            {
                if (op.FileName == "")
                    //Default
                    op.InitialDirectory = "\\";
                else
                {
                    ///Start at current directory
                    System.IO.FileInfo inf = new System.IO.FileInfo(op.FileName);
                    op.InitialDirectory = inf.Directory.ToString(); ;
                }

                dr = op.ShowDialog();
                if (dr == System.Windows.Forms.DialogResult.OK)
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(op.FileName))
                    {
                        richTextBox1.Text = sr.ReadToEnd();
                    }
                    sf.FileName = op.FileName;
                    System.IO.FileInfo inf = new System.IO.FileInfo(op.FileName);
                    this.Text = "Compact 2013 Notepad: " + inf.Name;
                    TextDirty = false;
                }
            }


        }

        private void newMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr;
            if (TextDirty)
            {
                dr = MessageBox.Show("Save Changes?", "Compact13Notepad", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,MessageBoxDefaultButton.Button1);
                if (dr == System.Windows.Forms.DialogResult.Cancel)
                    return;
                else if (dr == System.Windows.Forms.DialogResult.Yes)
                {
                    SaveCancelled = false;
                    saveMenuItem_Click(null, null);
                    if (!SaveCancelled)
                    {
                        richTextBox1.Text = "";
                        ClearDialogs();
                    }
                }
                else
                {
                    richTextBox1.Text = "";
                    ClearDialogs();
                }

            }
            else
            {
                richTextBox1.Text = "";
                ClearDialogs();
            }

        }

        #region Edit

        private void selectAllMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.SelectAll();
        }

        private void cutMenuItem_Click(object sender, EventArgs e)
        {
            string str = richTextBox1.SelectedText;
            Clipboard.SetDataObject( (object) str);
            richTextBox1.SelectedText = "";
        }

        private void copypMenuItem_Click(object sender, EventArgs e)
        {
            string str = richTextBox1.SelectedText;
            Clipboard.SetDataObject(str);
        }

        private void pasteMenuItem_Click(object sender, EventArgs e)
        {

            IDataObject iData = Clipboard.GetDataObject();

            // Determines whether the data is in a format you can use. 
            if (iData.GetDataPresent(DataFormats.Text))
            {
                // Yes it is, so display it in a text box.
                richTextBox1.SelectedText = (String)iData.GetData(DataFormats.Text);
            }
            else
                richTextBox1.SelectedText = "";
        }

        private void deteteMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.SelectedText = "";
        }

        #endregion

        private void timeDateMenuItem_Click(object sender, EventArgs e)
        {
            DateTime Now = DateTime.Now;
            richTextBox1.SelectedText = Now.ToShortTimeString() + " " + Now.ToShortDateString();
        }




        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            searchFor = textBox1.Text;
            searchStart = 0;
        }



        private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case System.Windows.Forms.Keys.F3:
                    menuItem19_Click(null, null);
                    e.Handled = true;
                    break;
                case System.Windows.Forms.Keys.F5:
                    timeDateMenuItem_Click(null, null);
                    e.Handled = true;
                    break;
                case System.Windows.Forms.Keys.N:
                    if (e.Modifiers== Keys.Control)
                    {
                        newMenuItem_Click(null, null);
                        e.Handled = true;
                    }
                    break;
                case System.Windows.Forms.Keys.O:
                    if (e.Modifiers == Keys.Control)
                    {
                        openMenuItem_Click(null, null);
                        e.Handled = true;
                    }
                    break;
                case System.Windows.Forms.Keys.S:
                    if (e.Modifiers == Keys.Control)
                    {
                        saveMenuItem_Click(null, null);
                        e.Handled = true;
                    }
                    break;
                //Replace
                case System.Windows.Forms.Keys.R:
                    if (e.Modifiers == Keys.Control)
                    {
                        menuItem20_Click(null, null);
                        e.Handled = true;
                    }
                    break;
            }
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {

        }



        private void menuItem2_Click(object sender, EventArgs e)
        {
            if (searchFor == "")
            {
                menuItem18.Enabled = false;
                menuItem19.Enabled = false;
            }
            if (replaceWith == "")
            {
                menuItem20.Enabled = false;
            }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            replaceWith = textBox2.Text;
        }

        
        private void menuItem36_Click(object sender, EventArgs e)
        {
            string str = richTextBox1.Text;
            Checkpoints.Push(str);
            CountCheckpoints();
        }

        private void menuItem35_Click(object sender, EventArgs e)
        {
            if (Checkpoints.Count != 0)
            {
                DialogResult dr;
                if (TextDirty)
                {
                    dr = MessageBox.Show("Save Changes?", "Compact13Notepad", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                    if (dr == System.Windows.Forms.DialogResult.Cancel)
                        return;
                    else if (dr == System.Windows.Forms.DialogResult.Yes)
                    {
                        SaveCancelled = false;
                        saveMenuItem_Click(null, null);
                        if (!SaveCancelled)
                        {
                            richTextBox1.Text = Checkpoints.Pop();
                            CountCheckpoints();
                        }
                    }
                    else
                    {
                        richTextBox1.Text = Checkpoints.Pop();
                        CountCheckpoints();
                    }

                }
                else
                {
                    richTextBox1.Text = Checkpoints.Pop();
                    CountCheckpoints();
                }

            }

        }

        private void menuItem37_Click(object sender, EventArgs e)
        {
            Checkpoints.Clear();
            CountCheckpoints();

        }

        private void menuItem34_Click(object sender, EventArgs e)
        {
        }

        private void CountCheckpoints()
        {
            int count = Checkpoints.Count;
            string strUnsaved="[Saved]   ";
            if (TextDirty)
                strUnsaved = "[Unsaved] ";


            if (Checkpoints.Count == 0)
            {
                menuItem35.Enabled = false;
                statusBar1.Text = strUnsaved + "There are no Checkpoints";

            }
            else
            {
                menuItem35.Enabled = true;
                statusBar1.Text = strUnsaved + count.ToString() + " Checkpoints";
            }
        }


        private void menuItem39_Click(object sender, EventArgs e)
        {
            menuItem39.Enabled = false;
            menuItem40.Enabled = true;
            Interop.SipShowIM(1);
        }

        private void menuItem40_Click(object sender, EventArgs e)
        {
            menuItem39.Enabled = true;
            menuItem40.Enabled = false;
            Interop.SipShowIM(0);
        }


    }
}
